﻿'Don't forget to support us by sharing this, and reporting bugs.
Imports System.Data.OleDb
Imports System.IO
'Chapter#3
Imports System.Drawing
Imports System.Data.Odbc
Imports System.Data.Odbc.OdbcConnection
Imports System.Data.Odbc.OdbcCommand

Public Structure Fotografia1PictureBox
    Shared Sub New()
        
    End Sub
End Structure
Public Class Clientes
    Dim IMG As Drawing.Image
    Dim Pic As Byte()
    Dim globalimg As String
    Dim MyStream As New IO.MemoryStream
    Public photo() As Byte
    Public modifica As Integer = 0
    Public Sub Mostrar()
        If guardar.Enabled = False Then
            guardar.Enabled = True
            cancelar.Enabled = True
            agregar.Enabled = False
            modificar.Enabled = False
            eliminar.Enabled = False
            imprimir.Enabled = False
            PanelArriba.Enabled = True
            PanelAbajo.Enabled = False

        Else
            cancelar.Enabled = False
            guardar.Enabled = False
            agregar.Enabled = True
            modificar.Enabled = True
            eliminar.Enabled = True
            imprimir.Enabled = True
            PanelArriba.Enabled = False
            PanelAbajo.Enabled = True


        End If
    End Sub
    Private Sub ClientesBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClientesBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.ClientesBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DbFireAndIceDataSet)

    End Sub

    Private Sub Clientes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'DbFireAndIceDataSet.tlog' table. You can move, or remove it, as needed.
        Me.TlogTableAdapter.Fill(Me.DbFireAndIceDataSet.tlog)
        'TODO: This line of code loads data into the 'DbFireAndIceDataSet.empleados' table. You can move, or remove it, as needed.
        ' Me.EmpleadosTableAdapter.Fill(Me.DbFireAndIceDataSet.empleados)
        'TODO: This line of code loads data into the 'DbFireAndIceDataSet.nominastipo' table. You can move, or remove it, as needed.
        Me.NominastipoTableAdapter.Fill(Me.DbFireAndIceDataSet.nominastipo)
        'TODO: This line of code loads data into the 'DbFireAndIceDataSet.empresas' table. You can move, or remove it, as needed.
        Me.EmpresasTableAdapter.Fill(Me.DbFireAndIceDataSet.empresas)
        'TODO: This line of code loads data into the 'DbFireAndIceDataSet.clientes' table. You can move, or remove it, as needed.
        Me.ClientesTableAdapter.Fill(Me.DbFireAndIceDataSet.clientes)
        FotografiaPictureBox.Image = My.Resources.url2
        Dim ms As New IO.MemoryStream
        FotografiaPictureBox.Image.Save(ms, Imaging.ImageFormat.Jpeg)
        Dim bytes() As Byte = ms.ToArray
        photo = bytes

        If PreciodefaultTextBox.Text = "1" Then

            PreciodefaultComboBox.SelectedItem = "Normal"

        End If
        If PreciodefaultTextBox.Text = "2" Then

            PreciodefaultComboBox.SelectedItem = "Visita"

        End If

    End Sub

    Private Sub PanelArriba_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PanelArriba.Paint
        'CodigoTextBox.Text = Format(CodigoTextBox, "###-###-###")
        'CodigoTextBox.SelStart = Len(CodigoTextBox.Text)
    End Sub

    Private Sub agregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agregar.Click
        modifica = 0
        IdclienteTextEdit.Text = ""
        'BindingNavigatorAddNewItem.PerformClick()
        IdempresaGridLookUpEdit.EditValue = ""
        ApellidoTextBox.Text = ""
        NombreTextBox.Text = ""
        'IdempresaGridLookUpEdit.EditValue = " "
        CodigoTextBox1.Text = ""
        IdnominaGridLookUpEdit.EditValue = Nothing
        IdempresaGridLookUpEdit.EditValue = Nothing
        EmailTextBox.Text = ""
        TelefonoTextEdit.Text = ""
        PreciodefaultComboBox.Text = ""
        ActivoCheckBox1.CheckState = CheckState.Checked
        PermitecreditoCheckBox.CheckState = CheckState.Unchecked
        PermiteplanillaCheckBox.CheckState = CheckState.Unchecked
        FotografiaPictureBox.Image = My.Resources.url2
        Dim ms As New IO.MemoryStream
        FotografiaPictureBox.Image.Save(ms, Imaging.ImageFormat.Jpeg)
        Dim bytes() As Byte = ms.ToArray
        photo = bytes
        Mostrar()
    End Sub

    Private Sub modificar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles modificar.Click
        IdclienteTextEdit.Enabled = False
        modifica = 1

        Mostrar()
    End Sub

    Private Sub eliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles eliminar.Click
        Dim opcion As Integer
        opcion = MsgBox("¿Está seguro que desea eliminar el registro?", MsgBoxStyle.YesNo + MsgBoxStyle.Question, "Eliminar registro")
        If opcion = vbYes Then
            Try
                ClientesTableAdapter.DeleteQuery(IdclienteTextEdit.EditValue)
                Me.ClientesTableAdapter.Fill(Me.DbFireAndIceDataSet.clientes)
            Catch ex As Exception
                MsgBox("Lo sentimos, el registro no puede ser eliminado ya que está relacionado con otras tablas", MsgBoxStyle.Critical, "Error")

                TlogTableAdapter.InsertQueryLogs(TlogTableAdapter.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, My.Resources.StringGlobal.prgNestor, "Pantalla clientes uso: DeleteQuery en boton eliminar", ex.Message, My.Resources.StringGlobal.mdlClientes, Date.Today, TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, sender.GetType.FullName.ToString)
            End Try


        End If
    End Sub

    Private Sub guardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles guardar.Click
        FechaafiliacionDateTimePicker.Value = FechaafiliacionDateTimePicker.Value.Date
        Dim precioventas As String
        If PreciodefaultComboBox.Text = "Normal" Then
            precioventas = 1
        End If
        If PreciodefaultComboBox.Text = "Visita" Then
            precioventas = 2

        End If

        If IdclienteTextEdit.Text = "" Then
            ErrorProvider1.SetError(IdclienteTextEdit, "Ingrese una identificación")
            Return
        End If
        ErrorProvider1.SetError(IdclienteTextEdit, Nothing)





            If (NombreTextBox.Text = "") Then
                ErrorProvider1.SetError(NombreTextBox, "Debe ingresar un nombre")
                Return

            End If
            ErrorProvider1.SetError(NombreTextBox, Nothing)




            If (ApellidoTextBox.Text = "") Then
                ErrorProvider1.SetError(ApellidoTextBox, "Debe ingresar un Apellido")
                Return
            End If
            ErrorProvider1.SetError(ApellidoTextBox, Nothing)



            If (IdempresaGridLookUpEdit.Text = "") Then
                ErrorProvider1.SetError(IdempresaGridLookUpEdit, "Debe seleccionar una empresa")

                Return

            End If


            ErrorProvider1.SetError(IdempresaGridLookUpEdit, Nothing)



        If modifica = 0 Then

            Dim xx As Integer
            xx = ClientesTableAdapter.ScalarQuerySabersiexitecliente(TextBox1verifica.Text)
            If xx = 1 Then
                ErrorProvider1.SetError(IdclienteTextEdit, "Ya existe un registro con esta idenfiticación")
                Return
            End If
            ErrorProvider1.SetError(IdclienteTextEdit, Nothing)


            Dim yy As Integer
            yy = ClientesTableAdapter.ScalarQuerySabersiexistecodigo(CodigoTextBox1.Text, IdempresaGridLookUpEdit.EditValue)


            If yy >= 1 Then
                ErrorProvider1.SetError(CodigoTextBox1, "Ya existe un registro con este código")
                Return

            End If
            ErrorProvider1.SetError(CodigoTextBox1, Nothing)

        End If
        







            If IdnominaGridLookUpEdit.Text = "" Then
                ErrorProvider1.SetError(IdnominaGridLookUpEdit, "Escoja un tipo de nómina")
                Return
            End If
            ErrorProvider1.SetError(IdnominaGridLookUpEdit, Nothing)



            If ActivoCheckBox1.CheckState = CheckState.Indeterminate Then
                ErrorProvider1.SetError(ActivoCheckBox1, "Verifique su estado")
                Return
            End If
            ErrorProvider1.SetError(ActivoCheckBox1, Nothing)


            If PreciodefaultComboBox.Text = "" Then

                ErrorProvider1.SetError(PreciodefaultComboBox, "Seleccione un precio ")
                Return

            End If

            ErrorProvider1.SetError(PreciodefaultComboBox, Nothing)




        Try

            If modifica = 1 Then
                ClientesTableAdapter.UpdateQuerytodo(NombreTextBox.Text, ApellidoTextBox.Text, IdempresaGridLookUpEdit.EditValue, CodigoTextBox1.Text, photo, IdnominaGridLookUpEdit.EditValue, IdclienteTextEdit.Text, EmailTextBox.Text, FechaafiliacionDateTimePicker.Value, TelefonoTextEdit.Text, 0, precioventas, ActivoCheckBox1.CheckState, PermitecreditoCheckBox.CheckState, PermiteplanillaCheckBox.CheckState, IdclienteTextEdit.EditValue)
                Mostrar()

            Else
                'ClientesBindingNavigatorSaveItem.PerformClick()

                
                ClientesTableAdapter.InsertQuery22(NombreTextBox.Text, ApellidoTextBox.Text, IdempresaGridLookUpEdit.EditValue, CodigoTextBox1.Text, photo, IdnominaGridLookUpEdit.EditValue, IdclienteTextEdit.Text, EmailTextBox.Text, FechaafiliacionDateTimePicker.Value, TelefonoTextEdit.Text, 0, precioventas, ActivoCheckBox1.CheckState, PermitecreditoCheckBox.CheckState, PermiteplanillaCheckBox.CheckState)
                Me.ClientesTableAdapter.Fill(Me.DbFireAndIceDataSet.clientes)
                Mostrar()
            End If
        Catch ex As Exception
            AlertControl1.AppearanceCaption.ForeColor = Color.Red
            AlertControl1.Show(Me, "Error", "Nose pudo guardar el registro")
            TlogTableAdapter.InsertQueryLogs(TlogTableAdapter.ScalarQueryCountLogs + 1, My.Forms.MDI.Iduser.Caption, My.Resources.StringGlobal.prgNestor, "Pantalla clientes , boton guardar, dentro del insert y update", ex.Message, My.Resources.StringGlobal.mdlClientes, Date.Today, TimeOfDay.TimeOfDay.ToString, My.Computer.Name, Name.ToString, sender.GetType.FullName.ToString)
            Mostrar()
        End Try

        AlertControl1.AppearanceCaption.ForeColor = Color.Green
        AlertControl1.Show(Me, "Advertencia", My.Resources.StringGlobal.msjGuardarExito)

    End Sub

    Private Sub cancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cancelar.Click
        ErrorProvider1.SetError(NombreTextBox, Nothing)
        ErrorProvider1.SetError(ApellidoTextBox, Nothing)
        ErrorProvider1.SetError(IdempresaGridLookUpEdit, Nothing)
        ErrorProvider1.SetError(PreciodefaultComboBox, Nothing)
        ErrorProvider1.SetError(TelefonoTextEdit, Nothing)
        ErrorProvider1.SetError(ActivoCheckBox1, Nothing)
        ErrorProvider1.SetError(IdclienteTextEdit, Nothing)
        ErrorProvider1.SetError(CodigoTextBox1, Nothing)
        IdclienteTextEdit.Enabled = True
        modifica = 0
        Mostrar()
        Me.ClientesTableAdapter.Fill(Me.DbFireAndIceDataSet.clientes)
    End Sub

    Private Sub imprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles imprimir.Click
        GridControl1.ShowPrintPreview()
    End Sub

   

    Public Shared Function getphoto(ByVal filePath As String) As Byte()
      
        Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
        Dim br As BinaryReader = New BinaryReader(fs)
        Dim photo() As Byte = br.ReadBytes(fs.Length)
        br.Close()
        fs.Close()
        Return photo
    End Function

   

    Private Sub FotografiaPictureBox_BackgroundImageChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        FotografiaPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub

    Private Sub GridControl1_FocusedViewChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.ViewFocusEventArgs) Handles GridControl1.FocusedViewChanged
        FotografiaPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub

    Private Sub FotografiaPictureBox_BackgroundImageLayoutChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        FotografiaPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub

    Private Sub GridControl1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GridControl1.Load
        FotografiaPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub

    Private Sub Button2_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'globalvar.formulario = "Clientes"

        Dim cam As New frmcamara(Me)
        cam.ShowDialog()
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim openFile2 As New System.Windows.Forms.OpenFileDialog()
        Dim img As Byte

        openFile2.DefaultExt = "Picture"
        openFile2.Filter = "jpg (*.jpg)|*.jpg|png (*.png*)|*.png*"

        openFile2.ShowDialog()
        If openFile2.FileNames.Length > 0 Then
            Dim filename As String
            For Each filename In openFile2.FileNames
                FotografiaPictureBox.Image = System.Drawing.Image.FromFile(openFile2.FileName)
                FotografiaPictureBox.SizeMode = PictureBoxSizeMode.StretchImage

                'Dim con2 As String = "DRIVER={PostgreSQL};User Id=postgres;Password=angely;Host=localhost;Database=dbFireAndIce;Schema=public"
                'Dim conn As New OdbcConnection(con2)
                'conn.Open()

                photo = getphoto(openFile2.FileName)
                MsgBox(openFile2.FileName)

               
            Next
        End If
    End Sub

    Private Sub CheckEdit1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckEdit1.CheckedChanged
        If CheckEdit1.CheckState = CheckState.Checked Then

            IdclienteTextEdit.Properties.DisplayFormat.FormatString = ""
            IdclienteTextEdit.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.None
            IdclienteTextEdit.Properties.Mask.EditMask = ""
            IdclienteTextEdit.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.None
            IdclienteTextEdit.Text = ""
        Else
            IdclienteTextEdit.Properties.DisplayFormat.FormatString = "\d\d\d\d\d\d\d\d\d\d\d\d\d"
            IdclienteTextEdit.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
            IdclienteTextEdit.Properties.EditFormat.FormatString = ""
            IdclienteTextEdit.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Custom
            IdclienteTextEdit.Properties.Mask.EditMask = "\d\d\d\d\d\d\d\d\d\d\d\d\d"
            IdclienteTextEdit.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx
            IdclienteTextEdit.Text = ""
        End If
    End Sub



 

    Private Sub EmailTextBox_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EmailTextBox.Leave
        Dim strCorreo As String
        strCorreo = EmailTextBox.Text
        Dim blnCorreo As Boolean
        Dim rgx As New System.Text.RegularExpressions.Regex("\w+([-+.´]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
        If rgx.IsMatch(strCorreo) Then
            blnCorreo = True

        Else
            blnCorreo = False
            AlertControl1.AppearanceCaption.ForeColor = Color.Red
            AlertControl1.Show(Me, "Error", "El Formato de correo electrónico no es válido")
            EmailTextBox.Focus()
        End If
    End Sub




    Private Sub TelefonoTextEdit_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TelefonoTextEdit.KeyPress
        '  If Char.IsLetter(e.KeyChar) Or e.KeyChar < Chr(47) Or e.KeyChar >= Chr(123) Or (e.KeyChar >= Chr(91) And e.KeyChar <= Chr(96)) Or ((e.KeyChar >= Chr(50)) And (e.KeyChar <= Chr(96))) Then
        If ((e.KeyChar <> Chr(8)) And (e.KeyChar <= Chr(47)) Or (e.KeyChar >= Chr(58))) Then
            e.Handled = True
            AlertControl1.AppearanceCaption.ForeColor = Color.Red
            AlertControl1.Show(Me, "Error", "Solo puede ingresar números")
            TelefonoTextEdit.Focus()

        ElseIf Char.IsSeparator(e.KeyChar) Then
            e.Handled = True
            AlertControl1.AppearanceCaption.ForeColor = Color.Red
            AlertControl1.Show(Me, "Error", "No debe ingresar espacios")
            TelefonoTextEdit.Focus()

        Else
            e.Handled = False

        End If
    End Sub

    Private Sub IdclienteTextEdit_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IdclienteTextEdit.Leave
        TextBox1verifica.Text = IdclienteTextEdit.Text

    End Sub

    Private Sub IdclienteTextEdit_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IdclienteTextEdit.EditValueChanged
        If PreciodefaultTextBox.Text Is DBNull.Value Then
        Else
            If PreciodefaultTextBox.Text = "1" Then
                PreciodefaultComboBox.Text = "Normal"
            End If
            If PreciodefaultTextBox.Text = "2" Then
                PreciodefaultComboBox.Text = "Visita"
            End If
          
        End If
        
    End Sub

    Private Sub TextBox1verifica_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1verifica.TextChanged
     
    End Sub


    Private Sub PreciodefaultComboBoxEdit_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreciodefaultComboBoxEdit.SelectedIndexChanged
        If PreciodefaultTextBox.Text = "1" Then

            PreciodefaultComboBox.SelectedItem = "Normal"

        End If
        If PreciodefaultTextBox.Text = "2" Then

            PreciodefaultComboBox.SelectedItem = "Visita"

        End If
    End Sub

    Private Sub PreciodefaultComboBoxEdit_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreciodefaultComboBoxEdit.SelectedValueChanged
        If PreciodefaultTextBox.Text = "1" Then

            PreciodefaultComboBox.SelectedItem = "Normal"

        End If
        If PreciodefaultTextBox.Text = "2" Then

            PreciodefaultComboBox.SelectedItem = "Visita"

        End If
    End Sub
End Class